package com.test;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.naming.java.javaURLContextFactory;
import org.junit.Test;

public class SimpleJava
{
    //    @Test
    public void tet() throws NamingException, SQLException
    {
        Hashtable<String, String> env = new Hashtable<String, String>();
        //        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        
        //        env.put(Context.INITIAL_CONTEXT_FACTORY, " org.apache.naming.factory.BeanFactory");
        env.put(Context.INITIAL_CONTEXT_FACTORY, " org.apache.naming.java.javaURLContextFactory");
        
        //        env.put(Context.PROVIDER_URL, "ldap://ldap.wiz.com:389");
        //        env.put(Context.SECURITY_PRINCIPAL, "joeuser");
        //        env.put(Context.SECURITY_CREDENTIALS, "joepassword");
        //        java:comp/env
        Context ic = new InitialContext(env);
        DataSource source = (DataSource) ic.lookup("java:comp/jdbc/TestDB");
        Connection con = source.getConnection();
    }
    
    @Test
    public void getsystem()
    {
        System.out.println(System.getenv(javax.naming.Context.INITIAL_CONTEXT_FACTORY));
        System.out.println(System.getProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY));
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        Context ic = null;
        try
        {
            ic = new InitialContext(env);
        }
        catch (NamingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        DataSource source = null;
        try
        {
            Context envContext = (Context) ic.lookup("java:comp/env/jdbc");
            source = (DataSource) envContext.lookup("jdbc/TestDB");
        }
        catch (NamingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try
        {
            Connection con = source.getConnection();
            Statement s = con.createStatement();
            s.executeQuery("select * from xxx");
        }
        catch (SQLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
